package git.soulbgm.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

/**
 * Json数据转换配置
 *
 * @author SoulBGM
 * @date 2024-09-26
 */
@Configuration
public class JsonDataConvertConfig {

    public JsonDataConvertConfig(ObjectMapper objectMapper, @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}") String dateFormat, @Value("${spring.jackson.time-zone:GMT+8}") String timeZone) {
        objectMapper.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);
        objectMapper.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        //序列化将Long转String类型
        SimpleModule longSimpleModule = new SimpleModule();
        longSimpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        longSimpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        longSimpleModule.addSerializer(long.class, ToStringSerializer.instance);

        //序列化将BigInteger转String类型
        SimpleModule bigIntegerModule = new SimpleModule();
        bigIntegerModule.addSerializer(BigInteger.class, ToStringSerializer.instance);

        //序列化将BigDecimal转String类型
        SimpleModule bigDecimalModule = new SimpleModule();
        bigDecimalModule.addSerializer(BigDecimal.class, ToStringSerializer.instance);

        objectMapper.registerModule(longSimpleModule);
        objectMapper.registerModule(bigIntegerModule);
        objectMapper.registerModule(bigDecimalModule);

        //设置Date输出格式
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
        objectMapper.setDateFormat(sdf);
    }

}
